/*
 * 
 *  This file is part of Sourceprojects.org Thracia.
 *  Copyright 2010 noctarius
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * 
 */
package org.sourceprojects.thracia.output.writer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.sourceprojects.thracia.ReporterConfig;
import org.sourceprojects.thracia.output.sender.QueuedReport;
import org.sourceprojects.thracia.report.beans.Report;
import org.sourceprojects.thracia.util.SequenceCounter;

/**
 * @author noctarius
 * 
 */
public abstract class AbstractOutputWriter<T extends Report, E extends Object> {
	protected class Filter implements FilenameFilter {

		public boolean accept(File dir, String name) {
			return name.toLowerCase().endsWith(".xml");
		}
	}

	private ReporterConfig config;

	private final T report;

	public AbstractOutputWriter(T report) {
		this.report = report;
	}

	public abstract QueuedReport flush();

	public ReporterConfig getConfig() {
		return config;
	}

	public T getReport() {
		return report;
	}

	public File getReportFile() throws IOException {
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
		final File reportdir = new File(config.getReportdir());

		if (!reportdir.exists()) {
			reportdir.mkdirs();
		}

		final File file = File.createTempFile("report"
				+ sdf.format(System.currentTimeMillis()), ".xml", reportdir);
		file.createNewFile();

		return file;
	}

	protected abstract E render();

	public void setConfig(ReporterConfig config) {
		this.config = config;
	}

	protected void removeExistingErrorLogsForReport() {
		String hash = getReport().getHash();

		File reportdir = new File(getConfig().getReportdir());

		if (!reportdir.exists())
			return;

		for (File r : reportdir.listFiles(new Filter())) {
			if (!r.exists() || r.isDirectory())
				continue;

			try {
				FileReader fr = new FileReader(r);

				char[] chars = new char[(int) r.length()];
				fr.read(chars);
				fr.close();

				String data = String.copyValueOf(chars);

				if (data.toString().contains(hash)) {
					int count = getSequenceNumber(data) + 1;

					if (count > getReport().getSequence()) {
						getReport().setSequence(count);
						SequenceCounter.getInstance().setCount(hash, count);
					}

					r.delete();
				}

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	protected DocumentBuilder createDocumentBuilder() throws Exception {
		final DocumentBuilderFactory factory = DocumentBuilderFactory
				.newInstance();

		return factory.newDocumentBuilder();
	}

	protected abstract int getSequenceNumber(String data);
}
